package com.xuyiwei.mayi.service;

import com.alibaba.fastjson.JSONObject;
import com.xuyiwei.mayi.adapter.MessageAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * Created by xuyiwei on 2019/4/28.
 */
@Service
@Slf4j
public class MailService implements MessageAdapter{
    @Value("${msg.subject}")
    private String subject;
    @Value("${msg.text}")
    private String text;
    @Value("${spring.mail.username}")
    private String fromMail;

    @Autowired
    private JavaMailSender mailSender; // 自动注入的Bean


    @Override
    public void sendMsg(JSONObject body) {
        if(body!=null){
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            String mail = body.getString("mail");
            mailMessage.setFrom(fromMail);
            mailMessage.setTo(mail);
            mailMessage.setSubject(subject);
            mailMessage.setText(text.replace("{}",mail));
            mailSender.send(mailMessage);
        }
    }
}
